﻿#include"stdafx.h"
#if defined LK_MEMORYBUFFERS_
namespace LK
{
	//清理未使用的内存块
	void MemoryBuffer::ClearNotUsingBuffer()
	{
		unsigned char* parr[sizeof(size_t) * 8] = { 0 };
		mt.Lock();
		size_t m = MinValues::template Of<index_t>();
		for (size_t i = 0; i < sizeof(size_t) * 8; ++i, m >>= 1)
			if ((mask&m) != 0) { mask ^= m; parr[i] = arr[i]; arr[i] = NULL; sarr[i] = 0; }
		mt.UnLock();
		for (size_t i = 0; i < sizeof(size_t) * 8; ++i)Memory::Free(parr[i]);
	}
	//获取一块不小于指定大小的内存，内存指针写入pPointer指向的指针变量中，返回一个mask
	size_t MemoryBuffer::GetBuffer(size_t size, unsigned char**pPointer)
	{
		mt.Lock();
		if (mask == 0){
			mt.UnLock(); 
			*pPointer = Memory::Malloc<unsigned char>(size);
			return 0;
		}
		size_t i = Bits::LeftZeroCount(mask);
		size_t m = MinValues::Of((index_t*)0);
		m >>= i;
		mask ^= m;
		mt.UnLock();
		if (sarr[i] >= size) { *pPointer = arr[i]; return m; }
		*pPointer = arr[i] = Memory::Realloc<unsigned char>(arr[i], sarr[i] = size);
		return m;
	}
	//释放指定的内存块
	void MemoryBuffer::ReleaseBuffer(size_t m, unsigned char*pointer)
	{
		if (m == 0) { Memory::Free(pointer); return; }
		mt.Lock();
		mask ^= m;
		mt.UnLock();
	}

}
#endif